// 确保这是一个模块（通过导出或导入语句）
export {}; // 这是一个空的导出语句，用于将文件标记为模块

// 在模块化环境中扩展全局 Array 接口
declare global {
    interface Array<T> {
        back(): T | undefined;
    }
}


// TODO: replace with Array.prototype.lastIndexOf
Array.prototype.back = function<T>(this: T[]): T | undefined {
    return this[this.length - 1];
};

type MIN_STACK_ITEM = {
    val: number,
    idx: number,
};

function sumSubarrayMins(arr: number[]): number {
    const MOD = 1e9+7;
    const arr_len = arr.length;
    const dp = new Array(arr_len+1);
    dp[0] = 0;
    const min_stack = [{val: 0, idx: 0}];
    for (let i = 1; i <= arr_len; i++)
    {
        const cur_val = arr[i-1];
        while (cur_val <= min_stack.back()!.val)
        {
            min_stack.pop();
        }
        const last_min_idx = min_stack.back()!.idx;
        const old_dp_val = dp[last_min_idx];
        const seg_min_sum = (i - last_min_idx) * (cur_val % MOD);
        dp[i] = (old_dp_val + seg_min_sum % MOD) % MOD;
        min_stack.push({val: cur_val, idx: i});
    }

    let ret_min_sum = 0;
    for (let i = 1; i <= arr_len; i++)
    {
        ret_min_sum += dp[i];
        ret_min_sum %= MOD;
    }
    return ret_min_sum;
};

const inputs = [
    [3,1,2,4],
    [11,81,94,43,3],
];
inputs.forEach((input_arr) => {
    console.log(input_arr, sumSubarrayMins(input_arr));
});